import type {ProColumns, ProFormInstance} from '@ant-design/pro-components';
import {ProTable} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, message, Modal} from 'antd';
import React, {useRef} from 'react';
import {testDatasourceConnectUsingPost} from "@/services/easyapi/eDatasource";

export type Props = {
  columns: ProColumns<API.PageDataSourcePageVo_>[];
  onCancel: () => void;
  onSubmit: (values: API.AddDatasourceParam) => Promise<void>;
  visible: boolean;
};

const CreateModal: React.FC<Props> = (props) => {
  const {visible, columns, onCancel, onSubmit} = props;
  const formRef = useRef<ProFormInstance<any>>();
  return (
    <Modal visible={visible} footer={null} onCancel={() => onCancel?.()}>
      <ProTable
        type="form"
        columns={columns}
        onSubmit={async (value) => {
          onSubmit?.(value);
        }}
        formRef={formRef}
        form={{
          submitter: {
            render: (props, doms) => {
              return [
                ...doms,
                <Button
                  type="primary"
                  key="testLink"
                  onClick={async () => {
                    await testDatasourceConnectUsingPost({
                      dataDesc: formRef.current?.getFieldsValue()['dataDesc'],
                      dataJson: formRef.current?.getFieldsValue()['dataJson'],
                      dataName: formRef.current?.getFieldsValue()['dataName'],
                      datasourcePassword: formRef.current?.getFieldsValue()['datasourcePassword'],
                      datasourceUsername: formRef.current?.getFieldsValue()['datasourceUsername'],
                      type: formRef.current?.getFieldsValue()['type'],
                    }).then(res => {
                      console.log(res)
                      if (res.code && res.code === 200) {
                        message.success('连接成功')
                      }
                      if (res.code && res.code !== 200) {
                        message.error('连接失败');
                      }
                    }).catch(err => {
                      message.error('连接失败')
                    });
                  }}
                  style={{marginLeft: 8}}
                >
                  测试链接
                </Button>,
              ];
            },
          },
        }}
      />
    </Modal>

  );
};
export default CreateModal;
